const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const User = require('../models/userSchema')
const Menu = require('../models/menuSchema')
const Role = require('../models/roleSchema')
const util = require('../utils/util')
const Counter = require('../models/counterSchema')
const md5 = require('md5')

router.prefix('/users')

router.post('/login', async (ctx) => {
  const { userName, userPwd } = ctx.request.body
  try {
    const user = await User.findOne(
      {
        userName,
        userPwd: md5(userPwd)
      },
      'userId userName userEmail state role deptId roleList'
    )

    const data = user._doc

    const token = jwt.sign(
      {
        data
      },
      'aicherish',
      { expiresIn: '1h' }
    )

    if (user) {
      data.token = token

      ctx.body = util.success(data)
    } else {
      ctx.body = util.fail('用户名或者密码错误')
    }
  } catch (error) {
    ctx.body = util.fail(error.msg)
  }
})

router.get('/list', async (ctx) => {
  const { userId, userName, state } = ctx.request.query
  const { page, skipIndex } = util.pager(ctx.request.query)

  const params = {}
  userId && (params.userId = userId)
  userName && (params.userName = userName)
  state && state !== '0' && (params.state = state)

  const query = User.find(params, { _id: 0, userPwd: 0 })
  const list = await query.skip(skipIndex).limit(page.pageSize)

  const total = await User.countDocuments(params)

  ctx.body = util.success({
    page: {
      ...page,
      total
    },
    list
  })
})

router.get('/all/list', async (ctx) => {
  const list = await User.find({}, 'userId userName userEmail')
  ctx.body = util.success(list)
})

router.post('/delete', async (ctx) => {
  const { userIds } = ctx.request.body
  const res = await User.updateMany({ userId: { $in: userIds } }, { state: 2 })

  if (res.modifiedCount) {
    ctx.body = util.success(res, `共删除成功${res.modifiedCount}条`)
    return
  }
  ctx.body = util.fail('删除失败')
})

router.post('/operate', async (ctx) => {
  const {
    userId,
    userName,
    userEmail,
    mobile,
    job,
    state,
    roleList,
    deptId,
    action
  } = ctx.request.body

  if (action === 'add') {
    if (!userName || !userEmail || !deptId) {
      ctx.body = util.fail('参数错误', util.CODE.CODE_PARAM_ERROR)
      return
    }
    const doc = await Counter.findOneAndUpdate(
      { id: 'userId' },
      { $inc: { sequence_value: 1 } },
      { new: true }
    )
    const res = await User.findOne(
      { $or: [{ userName }, { userEmail }] },
      '_id userName userEmail'
    )
    if (res) {
      ctx.body = util.fail(
        `用户已存在，信息如下：${res.userName}-${res.userEmail}`
      )
      return
    }
    const user = new User({
      userId: doc.sequence_value,
      userName,
      userPwd: md5('123456'),
      userEmail,
      role: 1,
      roleList,
      job,
      state,
      deptId,
      mobile
    })
    user.save()
    ctx.body = util.success(`用户创建成功`)
  } else {
    if (!deptId) {
      ctx.body = util.fail('部门不能为空', util.CODE.CODE_PARAM_ERROR)
      return
    }
    const res = await User.findOneAndUpdate(
      { userId },
      { job, state, roleList, deptId, mobile }
    )

    if (res) {
      ctx.body = util.success(res, `更新成功`)
    } else {
      ctx.body = util.fail('更新失败')
    }
  }
})

router.get('/getPermissionList', async (ctx) => {
  const authorization = ctx.request.headers.authorization
  const { data } = util.decoded(authorization)
  let menuList = await getMenuList(data.role, data.roleList)
  let actionList = getActionList(JSON.parse(JSON.stringify(menuList)))
  ctx.body = util.success({ menuList, actionList })
})

async function getMenuList(userRole, roleKeys) {
  let rootList = []
  if (userRole === 0) {
    rootList = (await Menu.find({})) || []
  } else {
    const roleList = await Role.find({ _id: { $in: roleKeys } })

    let permissionList = []

    roleList.map((role) => {
      const { checkedKeys, halfCheckedKeys } = role.permissionList
      permissionList = permissionList.concat([
        ...checkedKeys,
        ...halfCheckedKeys
      ])
    })

    // 去重
    permissionList = [...new Set(permissionList)]
    rootList = await Menu.find({ _id: { $in: permissionList } })
  }
  return util.getTreeMenu(rootList, null, [])
}

function getActionList(list) {
  const actionList = []

  const deep = (arr) => {
    while (arr.length) {
      let item = arr.pop()
      if (item.action) {
        item.action.map((action) => {
          actionList.push(action.menuCode)
        })
      }
      if (item.children && !item.action) {
        deep(item.children)
      }
    }
  }
  deep(list)

  return actionList
}

module.exports = router
